<?php
namespace control;

/*
*派遣结算类
*/

class laborSettleClass extends adIndexClass
{
    private const page = 'laborSettle';
    private const title = '派遣结算';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'company'      => [
                        'name'  => "派遣单位",
                        'width' => 200,
                    ],
                    'targetDate' => [
                        'name'  => "单据日期",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'classify'         => [
                        'name'  => '业务类型',
                        'width' => 200,
                    ],
                    'saleMoney'          => [
                        'name'  => '应付金额(' . static::$unit . ')',
                        'width' => 250,
                    ],
                    'recMoney'    => [
                        'name'  => '实际付款金额(' . static::$unit . ')',
                        'width' => 250,
                    ],
                    'balance'    => [
                        'name'  => '应付款余额(' . static::$unit . ')',
                        'width' => 250,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "派遣单位"     => text(array("name" => "name")),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch($cla=self::page)
    {
        //like查询数组
        $like = array(
            'b.name' =>  $this->post('name'),
            'a.orderNo' =>  $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'a.type'=>'派遣单位',
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'targetDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'targetDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => "record as a join labor_company as b on a.typeId = b.id",
            'field'=>"b.orderNo,b.name,a.*",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            if (in_array($array['classify'], ['劳动报酬付款'])) {
                $recMoney = $array['money'];
                $saleMoney = 0;
            } else {
                $saleMoney =  $array['money'];
                $recMoney =0;
            }
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "company":
                        $company = query('labor_company',"id = '$array[typeId]'");
                        $row[] = $company['name'];
                        break;
                    case "saleMoney":
                        $row[] = $saleMoney;
                        break;
                    case "recMoney":
                        $row[] = $recMoney;
                        break;
                    case "balance":
                        $row[] = $array['balance']!=0?$array['balance']:0;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "record as a join labor_company as b on a.typeId = b.id",
                    'field'=>"b.orderNo,b.name,a.*",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by targetDate desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                if (in_array($array['classify'], ['劳动报酬付款'])) {
                    $recMoney = $array['money'];
                    $saleMoney = 0;
                } else {
                    $saleMoney =  $array['money'];
                    $recMoney =0;
                }
                $company = query('labor_company',"id = '$array[typeId]'");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '派遣单位'=>$company['name'],
                            '单据日期'=>$array['targetDate'],
                            '单据编号'=>$array['orderNo'],
                            '业务类型'=>$array['classify'],
                            '应付金额'=>$saleMoney,
                            '实际付款金额'=>$recMoney,
                            '应付款余额'=>self::lostZero($array['balance']),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了派遣结算表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "派遣结算表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'派遣单位',
                    'aliasName'=>'派遣单位',
                ],
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'业务类型',
                    'aliasName'=>'业务类型',
                ],
                [
                    'columnName'=>'应付金额',
                    'aliasName'=>'应付金额',
                ],
                [
                    'columnName'=>'实际付款金额',
                    'aliasName'=>'实际付款金额',
                ],
                [
                    'columnName'=>'应付款余额',
                    'aliasName'=>'应付款余额',
                ],
            ]
        };
    }
}

